var ResumeList={
   useUndo:true,
   do_save:function(resumes){
      if(!$.isArray(resumes)){
         resumes=[resumes];
      }

      var oldActions = [];
      var nresumes = []; 
      $.each(resumes,function(index,resume) {
         var saveAction = $('tr').filterAttr('data-id',resume).children("td.resumeactions").find(".action.save");
         if(saveAction.length <= 0)
            return true;
         saveAction.tooltip('hide'); 
         oldActions[nresumes.length] = saveAction[0].outerHTML;
         nresumes[nresumes.length++] = resume; 
         saveAction[0].outerHTML = '<img class="loading saveloading" data-action="Save" src="'+ OC.imagePath('core', 'loading.gif') +'">';
      })

      $.ajax({
         type: "POST",
         url: OC.filePath('resumes', 'ajax', 'save.php'),
         data: {ids:JSON.stringify(nresumes)},
         dataType: 'json',
         beforeSend: function(xhr, settings) {
            $('#headerName .save').each(function(){
               if(!showLoading($(this), settings, null, {button:true}))
                  return false;
            });
         },
         success: function(result){
            if (result.status == 'success') {
               $.each(nresumes,function(index,resume){
                  var tr = $('tr').filterAttr('data-id',resume);
                  /* in /All mode, change html only */
                  tr.attr('data-saved', 1).addClass('saved');
                  var saveAction = tr.children("td.resumeactions").find(".loading");
                  if(saveAction.length >0) {
                     /* now it's saved. change it to to saved */
                     var html = '<a href="#" class="action unsave" data-action="unsave" title="' + t('resumes', 'Unsave') + '">';
                     html += '</a>';
                     saveAction[0].outerHTML = html;
                     tr.children("td.resumeactions").find(".action.unsave").tooltip().data('action', 'Unsave');
                  }
               });
               procesSelection();
            } else {
               $.each(nresumes,function(index,resume) {
                  var saveAction = $('tr').filterAttr('data-id',resume).children("td.resumeactions").find(".loading");
                  if(saveAction.length >0 && typeof(oldActions[index]) != 'undefined')
                     saveAction[0].outerHTML = oldActions[index];
               });
               OC.Notification.showHtml(result.error+'<span class="undo tclose">'+t('resumes', 'Close')+'</span>', 3000);
            }
         }
      })
   },

   do_unsave:function(resumes){
      if(!$.isArray(resumes)){
         resumes=[resumes];
      }

      var oldActions = [];
      var nresumes = []; 
      $.each(resumes,function(index,resume) {
         var unsaveAction = $('tr').filterAttr('data-id',resume).children("td.resumeactions").find(".action.unsave");
         if(unsaveAction.length <= 0)
            return true; 

         unsaveAction.tooltip('hide'); 
         oldActions[nresumes.length] = unsaveAction[0].outerHTML;
         nresumes[nresumes.length++] = resume; 
         unsaveAction[0].outerHTML = '<img class="loading saveloading" data-action="Unsave" src="'+ OC.imagePath('core', 'loading.gif') +'">';
      })

      $.ajax({
         type: "POST",
         url: OC.filePath('resumes', 'ajax', 'unsave.php'),
         data: {ids:JSON.stringify(nresumes)},
         dataType: 'json',
         beforeSend: function(xhr, settings) {
            $('#headerName .unsave').each(function(){
               if(!showLoading($(this), settings, null, {button:true}))
                  return false;
            });
         },
         success: function(result){
            if (result.status == 'success') {
               $.each(nresumes,function(index,resume){
                  var tr = $('tr').filterAttr('data-id',resume);
                  if(tr.attr('data-type') == 'saved') {
                     tr.remove(); 
                  }
                 else {
                     /* in /All mode, change html only */
                     tr.attr('data-saved', 0).addClass('unsaved');
                     var unsaveAction = tr.children("td.resumeactions").find(".loading");
                     if(unsaveAction.length >0) {
                        /* now it's saved. change it to to saved */
                        var html = '<a href="#" class="action save" data-action="save" title="'+ t('resumes', 'Save') +'">';
                        html += '</a>';
                        unsaveAction[0].outerHTML = html;
                        tr.children("td.resumeactions").find(".action.save").tooltip().data('action', 'Save');
                     }
                  }
               });
               procesSelection();
            } else {
               $.each(nresumes,function(index,resume) {
                  var unsaveAction = $('tr').filterAttr('data-id',resume).children("td.resumeactions").find(".loading");
                  if(unsaveAction.length >0 && typeof(oldActions[index]) != 'undefined')
                     unsaveAction[0].outerHTML = oldActions[index];
               });
               OC.Notification.showHtml(result.error+'<span class="undo tclose">'+t('resumes', 'Close')+'</span>', 3000);
            }
         }
      })
   },

   do_trash:function(resumes){
      if(!$.isArray(resumes)){
         resumes=[resumes];
      }

      var oldActions = []; 
      var nresumes = []; 
      $.each(resumes,function(index,resume) {
         var deleteAction = $('tr').filterAttr('data-id',resume).data('permissions') & OC.PERMISSION_DELETE;
         if(!deleteAction)
            return true; 
         nresumes[nresumes.length++] =  resume; 
      })

      $.ajax({
         type: "POST",
         url: OC.filePath('resumes', 'ajax', 'delete.php'),
         data: {ids:JSON.stringify(nresumes)},
         dataType: 'json',
         beforeSend: function(xhr, settings) {
            $('#headerName .delete').each(function(){
               if(!showLoading($(this), settings, null, {button:true}))
                  return false;
            });
         },
         success: function(result){
            if (result.status == 'success') {
               if(nresumes.length > 1) 
                  OC.Notification.showHtml(nresumes.length + '份简历被删除进回收站。'+'<span class="undo restore">'+t('resumes', 'undo')+'</span>', 3000);
               else if(nresumes.length >= 1){
                  var tr = $('tr').filterAttr('data-id',nresumes[0]); 
                  OC.Notification.showHtml(tr.attr('data-name') + ' － 应聘职位<strong>'+ tr.find("a.jobposition").text() + '</strong>的简历被删除进回收站。'+'<span class="undo restore">'+t('resumes', 'undo')+'</span>', 3000);
               }
               /* remember deleted resumes */     
               ResumeList.trashedResumes = nresumes; 
               $.each(nresumes,function(index,resume){
                  var tr = $('tr').filterAttr('data-id',resume);
                  tr.hide().addClass("trashed").next().hide().addClass("trashed");
                  var deleteAction = tr.children("td.resumeactions").find(".loading");
                  if(deleteAction.length >0 && typeof(oldActions[index]) != 'undefined')
                     deleteAction[0].outerHTML = oldActions[index];

               });
               procesSelection();
            } else {
               $.each(nresumes,function(index,resume) {
                  var deleteAction = $('tr').filterAttr('data-id',resume).children("td.resumeactions").find(".loading");
                  if(deleteAction.length >0 && typeof(oldActions[index]) != 'undefined')
                     deleteAction[0].outerHTML = oldActions[index];
               });
               OC.Notification.showHtml(result.error+'<span class="undo tclose">'+t('resumes', 'Close')+'</span>', 3000);
            }
         }
      })
   },

   do_restore: function(resumes) {
      if(!$.isArray(resumes)){
         resumes=[resumes];
      }

      var oldActions = []; 
      var nresumes = []; 
      $.each(resumes,function(index,resume) {
         var tr = $('tr').filterAttr('data-id',resume); 
         /* let see if it's just trashed, and in last trashed list; we don't undo the resumes before last list */
         if(tr.hasClass("trashed") && $.isArray(resume, ResumeList.trashedResumes) != -1) {
            nresumes[nresumes.length++] = resume;
            return true; 
         }
            
         var restoreAction = tr.children("td.resumeactions").find(".action.restore");
         if(restoreAction.length <= 0)
            return true; 
         //destroy restore tooltip first 
         restoreAction.tooltip('destroy');

         oldActions[nresumes.length] = restoreAction[0].outerHTML;
         nresumes[nresumes.length++] = resume;
         restoreAction[0].outerHTML = '<img class="loading" data-action="Delete" src="'+ OC.imagePath('core', 'loading.gif') +'">';
      })

      $.ajax({
         type: "POST",
         url: OC.filePath('resumes', 'ajax', 'restore.php'),
         data: {ids:JSON.stringify(nresumes)},
         dataType: 'json',
         beforeSend: function(xhr, settings) {
            $('#headerName .restore').each(function(){
               if(!showLoading($(this), settings, null, {button:true}))
                  return false;
            });
         },
         success: function(result){
            if (result.status == 'success') {
               if(nresumes.length >= 1) 
                  OC.Notification.showHtml(nresumes.length + '份简历已被恢复。', 3000);

               $.each(nresumes,function(index,resume){
                  var tr = $('tr').filterAttr('data-id',resume);
                  if(tr.hasClass("trashed")) {
                     tr.show().removeClass("trashed").next().show().removeClass("trashed");
                  } else {
                     tr.next().remove();
                     tr.remove();
                  }
               });
               procesSelection();
            } else {
               $.each(nresumes,function(index,resume) {
                  var tr = $('tr').filterAttr('data-id',resume);
                  if(tr.hasClass("trashed"))
                     return true; 
                  var restoreAction = tr.children("td.resumeactions").find(".loading");
                  if(restoreAction.length >0 && typeof(oldActions[index]) != 'undefined')
                     restoreAction[0].outerHTML = oldActions[index];
               });
               OC.Notification.showHtml(result.error+'<span class="undo tclose">'+t('resumes', 'Close')+'</span>', 3000);
            }
         }
      })
   },

   do_permdelete:function(resumes){
      if(!$.isArray(resumes)){
         resumes=[resumes];
      }
      var oldActions = []; 
      var nresumes = []; 
      $.each(resumes,function(index,resume) {
         var deleteAction = $('tr').filterAttr('data-id',resume).children("td.resumeactions").find(".action.permdelete");
         if(deleteAction.length <= 0)
            return true; 
 
         //destroy attached tooltip first 
         deleteAction.tooltip('destroy');        

         oldActions[nresumes.length] = deleteAction[0].outerHTML;
         nresumes[nresumes.length++] = resume; 
         deleteAction[0].outerHTML = '<img class="loading" data-action="Delete" src="'+ OC.imagePath('core', 'loading.gif') +'">';
      })

      $.ajax({
         type: "POST",
         url: OC.filePath('resumes', 'ajax', 'permdelete.php'),
         data: {ids:JSON.stringify(nresumes)},
         dataType: 'json',
         beforeSend: function(xhr, settings) {
            $('#headerName .permdelete').each(function(){
               if(!showLoading($(this), settings, null, {button:true}))
                  return false;
            });
         },
         success: function(result){
            if (result.status == 'success') {
               $.each(nresumes,function(index,resume){
                  var tr = $('tr').filterAttr('data-id',resume);
                  tr.next().remove();
                  tr.remove();
               });
               procesSelection();
            } else {
               $.each(nresumes,function(index,resume) {
                  var deleteAction = $('tr').filterAttr('data-id',resume).children("td.resumeactions").find(".loading");
                  if(deleteAction.length >0 && typeof(oldActions[index]) != 'undefined')
                     deleteAction[0].outerHTML = oldActions[index];
               });
               OC.Notification.showHtml(result.error+'<span class="undo tclose">'+t('resumes', 'Close')+'</span>', 3000);
            }
         }
      })
   },
   
   do_invite:function(resumes){
      if(!$.isArray(resumes)){
         resumes=[resumes];
      }
      var msg = '';
      var sub_msg = '';
      var jobsysfailed = 0;
      var setupfailed = 0;
      var totalfailed = 0;
      var nresumes = [];
      $.each(resumes,function(index,resume) {
         if(resume.jobsystem) {
            jobsysfailed++;
         } else if (resume.jobsystem == 0 && resume.issetup == 0) {
            setupfailed++;
         } else {
            nresumes[nresumes.length++] =  resume.id;
         }
      });
      totalfailed = jobsysfailed+setupfailed;

      // Make msg
      if(nresumes.length >= 1) {
         msg = nresumes.length+'个邀请发送成功';
         msg += totalfailed > 0 ? '，' : '。';
      }
      if (totalfailed > 0) {
         msg += totalfailed+'个邀请发送失败：';
         if (totalfailed == 1) {
            sub_msg += jobsysfailed > 0 ? '简历未分配职位' : (setupfailed > 0 ? '职位未设置笔试评测或性格评测' : '已发送过邀请');
         }
         if (sub_msg.length <= 0) {
            if (jobsysfailed > 0) {
               sub_msg += jobsysfailed+'份简历未分配职位';
            }
            if (setupfailed > 0) {
               sub_msg += sub_msg.length > 0 ? '，' : '';
               sub_msg += setupfailed+'份简历职位未设置笔试评测或性格评测'
            }
         }
         msg += sub_msg;
      }

      // All chosen resume failed
      if (nresumes.length <= 0) {
         OC.Notification.showHtml(msg, 3000);
         procesSelection();
         return false;
      }

      $.ajax({
         type: "POST",
         url: OC.filePath('resumes', 'ajax', 'invitejobseeker.php'),
         data: {ids:JSON.stringify(nresumes)},
         dataType: 'json',
         beforeSend: function(xhr, settings) {
            $('#headerName .invite').each(function(){
               if(!showLoading($(this), settings, null, {button:true}))
                  return false;
            });
         },
         success: function(result){
            if (result.status == 'success') {
               if(msg) {
                  OC.Notification.showHtml(msg, 3000);
               } else {
                  OC.Notification.showHtml("邀请发送成功", 3000);
               }
               procesSelection();
            } else {
               OC.Notification.showHtml(result.error+'<span class="undo tclose">'+t('resumes', 'Close')+'</span>', 3000);
            }
         }
      })
   },
   
   do_infolder:function(resumes){
      if(!$.isArray(resumes)){
         resumes=[resumes];
      }

      var nresumes = []; 
      $.each(resumes,function(index,resume) {
         nresumes[nresumes.length++] =  resume; 
      });

      if(nresumes.length >= 1) {
         var scrolltops = $(window).scrollTop();
         $('#infolder_modal').css("top",scrolltops+75+"px").modal();
         
         $.ajax({
            type: "GET",
            url: OC.filePath('resumes', 'ajax', 'getinfolderlist.php'),
            data: {ids:JSON.stringify(nresumes)},
            beforeSend: function(xhr, settings) {
               showLoading($("#infolder_body"));
            },
            cache: false,
            success: function(result){
               $("#infolder_body").html(result);
            }
         });
      }
   }

};

$(document).ready(function(){
   $('#notification').hide();
   $('#notification').on('click', '.undo', function(){
      if($(this).hasClass("restore")) {
         ResumeList.do_restore(ResumeList.trashedResumes);
      }

      OC.Notification.hide();
      return false;
   });

   ResumeList.useUndo=(window.onbeforeunload)?true:false;
   $(window).unload(function (){
      $(window).trigger('beforeunload');
   });

});
